package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.OrderedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //@Scheduled(cron = "0/10 * * * * ?")
    public void handlerTimeOutorder() {
        log.info("未处理支付超时订单");
        //1、根据状态、订单查询未支付超时订单
        LocalDateTime dateTime = LocalDateTime.now().minusSeconds(15);
        List<Orders> orders = orderMapper.getByStatusAndTime(Orders.PENDING_PAYMENT, dateTime);

        orders.forEach(o -> {
            o.setStatus(Orders.CANCELLED);
            o.setCancelReason("订单超时");
            o.setCancelTime(LocalDateTime.now());
            orderMapper.update(o);
        });
    }

    /**
     * 处理“派送中”状态的订单
     */
    //@Scheduled(cron = "0/10 * * * * ?")
    public void processDeliveryOrder() {
        log.info("处理派送中订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }

}
